package com.ces.knacky.controller.tools;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ces.knacky.framework.controller.ListController;
import com.ces.knacky.model.Auction;
import com.ces.knacky.model.Item;

/**
 * This controller retrieves and displayed auction items.
 * @author shivangi_walvekar
 *
 */
@Controller
public class ListAuctionItemController extends ListController<Item>{

	private String selectedAuction;

	/**
	 * 
	 * @return auctionDescription
	 */

	public String getSelectedAuction() {
		return selectedAuction;
	}

	/**
	 * 
	 * @param auctionDescription
	 */
	@ModelAttribute("selectedAuction")
	public void setSelectedAuction(String selectedAuction) {
		this.selectedAuction = selectedAuction;
	}

	@RequestMapping("/listAuctionItems.htm")
	public String execute(HttpServletRequest request) {
		if (null != getSelectedAuction() && (!getSelectedAuction().isEmpty())) {
			 HttpSession session = request.getSession(true);
			 Auction auction = (Auction) commonService.findFirstByDescription(Auction.class,
			 getSelectedAuction());
			 session.setAttribute("selectedAuctionId",auction.getId());
			 listEntity = getAuctionItems(auction.getId());
		}
		// If user has selected a category ,then retrieve items for that
		// category.
		 else {
			listEntity = (List<Item>) commonService
					.list("SELECT item from Item item");
		}
		return "listAuctionItems";
	}

	private List<Item> getAuctionItems(int auctionId) {		
		// Load the auction object.
		Auction auction = (Auction) commonService.load(
				Auction.class, auctionId);
		if (auction == null) {
			// TODO - log and throw application specific exception
			System.out.println("Auction with descirption " + selectedAuction
					+ " does not exist !");
		}
		// Fetch the auction items
		listEntity = (List<Item>) commonService
				.list("SELECT distinct item from Item as item,Auction as auction,AuctionItem as "
						+ "auctionItem where item.id = auctionItem.item.id and " +
						"auction.id=auctionItem.auction.id and auction.id = " + auction.getId());
		if (listEntity != null) {
			System.out.println("size of auctionItems = " + listEntity.size());

		}
		return listEntity;
	}
	
}
